﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.IO;

namespace dzs.Web.supply
{
    public partial class ListSupplyPlan : System.Web.UI.Page
    {
        Maticsoft.BLL.supplyPlan sm = new Maticsoft.BLL.supplyPlan();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["login"] != null)
                {
                    DataSet ds = Session["login"] as DataSet;

                    int roles_id = Convert.ToInt32(ds.Tables[0].Rows[0]["roles_id"].ToString());
                    int user_id = Convert.ToInt32(ds.Tables[0].Rows[0]["user_id"].ToString());

                    Bind(user_id);
                }
            }
        }

        private void Bind(int user_id)
        {
            #region
            //string str = " user_id= " + user_id;
            //str += " and technicalDataStatus ='已确认'  ";//技术资料确认
          
            //if (!string.IsNullOrEmpty(txt_material.Text))
            //{
            //    str += " and material like '%" + txt_material.Text + "%' ";
            //}
            //if (!string.IsNullOrEmpty(txt_projectName.Text))
            //{
            //    str += " and projectName like '%" + txt_projectName.Text + "%' ";
            //}
            //if (!string.IsNullOrEmpty(txt_supplier.Text))
            //{
            //    str += " and sname like '%" + txt_supplier.Text + "%' ";
            //}
            //if (!string.IsNullOrEmpty(txt_ghqStart.Text) )
            //{
            //    str += " and supplyDate >='"+txt_ghqStart.Text+"' ";
            //}
            //if (!string.IsNullOrEmpty(txt_ghqEnd.Text))
            //{
            //    str += " and supplyDate <='" + txt_ghqEnd.Text + "' ";
            //}
            #endregion

            int count = 0;//总页数

            string isMonthSupplyPlan = null;

            if (this.rdo_wsc.Checked)//未生成月供计划
            {
                isMonthSupplyPlan = "否";
            }
            if (this.rdo_ysc.Checked)//已生成月供计划
            {
                isMonthSupplyPlan = "是";
            }


            #region 下月供应计划起始结束时间 以当前系统时间为基准
            List<dzs.Model.configinfo> cm = new dzs.BLL.configinfo().GetModelList("");//获取时间结算日期

            DateTime monthEndTime;//本月供应计划结束时间
            DateTime monthStartTime;//本月供应计划起始时间

            dzs.Model.configinfo c = cm[0];
            int day = DateTime.Today.Day;

            if (day <= c.ygyjs)
            {
                monthStartTime = DateTime.Parse(DateTime.Today.ToString("yyyy-MM-" + c.ygyqs + ""));
                monthEndTime = DateTime.Parse(DateTime.Today.AddMonths(1).ToString("yyyy-MM-" + c.ygyjs + ""));
            }
            else
            {
                monthStartTime = DateTime.Parse(DateTime.Today.AddMonths(1).ToString("yyyy-MM-" + c.ygyqs + ""));
                monthEndTime = DateTime.Parse(DateTime.Today.AddMonths(2).ToString("yyyy-MM-" + c.ygyjs + ""));
            }
            #endregion
            DataSet ds = sm.GetListSumInnumsInfo(user_id,monthEndTime,txt_material.Text,txt_projectName.Text,
                txt_supplier.Text, txt_ghqStart.Text, txt_ghqEnd.Text,isMonthSupplyPlan,
                this.AspNetPager1.CurrentPageIndex, this.AspNetPager1.PageSize, out count);

            //DataSet ds = sm.GetListSumInnumsInfo(str);

            this.AspNetPager1.RecordCount = count;

            DataTable dt = ds.Tables[0];

            //DataTable dt_source = dt.Clone();

            DataTable dt_source = dt.Copy();

            dt_source.Columns.Add("flagEarlyGreen", typeof(System.String));//有早到货情况标示
            dt_source.Columns.Add("flagLateRed", typeof(System.String));//有晚到货情况标示
            //dt_source.Columns.Add("isMonthSupplyPlan", typeof(System.String));//是否制定了月供应计划标示

            #region 
            //foreach (DataRow row in dt.Rows)
            //{
            //    decimal innums = decimal.Parse(row["innums"].ToString());
            //    decimal num = decimal.Parse(row["num"].ToString());
            //    string isEarly = row["isEarly"].ToString();
            //    DateTime supplyDate = DateTime.Parse(row["supplyDate"].ToString());

            //    if (isEarly == "True")
            //    {
            //        dt_source.ImportRow(row);
            //    }
            //    else if (innums < num)//已入库数量 < 计划数量或者已入库数量为null时
            //    {
            //        if (supplyDate <= monthEndTime)//供货期小于下月计划结束时间
            //        {
            //            dt_source.ImportRow(row);
            //        }
            //    }

            //}

            
            #endregion

            DataTable dt_dealSource = DealEarlyLate(user_id, cm, c, dt_source);
            this.GridView1.DataSource = dt_dealSource;
            this.GridView1.DataBind();
            this.lbl_dsCount.Text = "当前共 " + count + " 条记录";

            DataTable dt_equipment = new dzs.BLL.equipmentManage().GetList("").Tables[0];

            this.ddl_equipmentMan.DataSource = dt_equipment;
            this.ddl_equipmentMan.DataTextField = "equipmentManageName";
            this.ddl_equipmentMan.DataValueField = "id";
            this.ddl_equipmentMan.DataBind();
            this.ddl_equipmentMan.Items.Insert(0, new ListItem("--未选择--","-1"));

            #region
            //if (this.rdo_all.Checked)//全部
            //{
            //    this.GridView1.DataSource = dt_dealSource;
            //    this.GridView1.DataBind();
            //    this.lbl_dsCount.Text = "当前共 " + count + " 条记录";
            //}
            //DataTable dt_newDealSource = dt_dealSource.Clone();
            //if (this.rdo_wsc.Checked)//未生成月供计划
            //{
            //    for (int i = 0; i < dt_dealSource.Rows.Count; i++)
            //    {
            //        DataRow row = dt_dealSource.Rows[i];

            //        if (row["isMonthSupplyPlan"].ToString() != "是")
            //        {
            //            dt_newDealSource.ImportRow(row);
            //        }
            //    }

            //    this.GridView1.DataSource = dt_newDealSource;
            //    this.GridView1.DataBind();

            //    //this.lbl_dsCount.Text = "当前共 " + dt_newDealSource.Rows.Count + " 条记录";
            //    //this.lbl_dsCount.Text = "当前共 " + count + " 条记录";
            //}

            //if (this.rdo_ysc.Checked)//已生成月供计划
            //{
            //    for (int i = 0; i < dt_dealSource.Rows.Count; i++)
            //    {
            //        DataRow row = dt_dealSource.Rows[i];

            //        if (row["isMonthSupplyPlan"].ToString() == "是")
            //        {
            //            dt_newDealSource.ImportRow(row);
            //        }
            //    }

            //    this.GridView1.DataSource = dt_newDealSource;
            //    this.GridView1.DataBind();

            //    //this.lbl_dsCount.Text = "当前共 " + dt_newDealSource.Rows.Count + " 条记录";
            //    //this.lbl_dsCount.Text = "当前共 " + count + " 条记录";
            //}
            #endregion

        }

        //处理早到货晚到货的方法，将不符合条件的DataRow删除掉
        private DataTable DealEarlyLate(int user_id, List<dzs.Model.configinfo> cm, dzs.Model.configinfo c, DataTable dt_source)
        {
            //DataTable dt = dt_source.Clone();

            //List<int> removeIndex = new List<int>();

            for (int i = 0; i < dt_source.Rows.Count; i++)
            {
                DataRow row_source = dt_source.Rows[i];

                string supplyPlanId = row_source["supplyPlanId"].ToString();

                #region 获取月供应计划详情列表 ds_mcount
                Maticsoft.BLL.monthSupplayPlan sms = new Maticsoft.BLL.monthSupplayPlan();

                string str_mcount = "  supplyPlanUser= " + user_id + " and supplyPlanId=" + supplyPlanId;

                //if (!string.IsNullOrEmpty(txt_material.Text))
                //{
                //    str_mcount += " and material like '%" + txt_material.Text + "%' ";
                //}
                //if (!string.IsNullOrEmpty(txt_projectName.Text))
                //{
                //    str_mcount += " and projectName like '%" + txt_projectName.Text + "%' ";
                //}
                //if (!string.IsNullOrEmpty(txt_supplier.Text))
                //{
                //    str_mcount += " and sname like '%" + txt_supplier.Text + "%' ";
                //}
                //if (!string.IsNullOrEmpty(txt_ghqStart.Text))
                //{
                //    str_mcount += " and supplyPlaneDate >='" + txt_ghqStart.Text + "' ";
                //}
                //if (!string.IsNullOrEmpty(txt_ghqEnd.Text))
                //{
                //    str_mcount += " and supplyPlaneDate <='" + txt_ghqEnd.Text + "' ";
                //}
                DataSet ds_mcount = sms.GetListInnums(str_mcount);
                #endregion

                if (ds_mcount != null)
                {
                    //if (ds_mcount.Tables[0].Rows.Count > 0)
                    //{
                    //    row_source["isMonthSupplyPlan"] = "是";//是否制定了月供应计划
                    //}

                    #region   获取月供应计划详情信息并根据详情信息处理 早到货情况 (是否上传了ERP)

                    //decimal innums = 0;
                    //decimal num = 0;

                    //if (!string.IsNullOrEmpty(row_source["innums"].ToString()))
                    //{
                    //    innums = decimal.Parse(row_source["innums"].ToString());

                    //}
                    //if (!string.IsNullOrEmpty(row_source["num"].ToString()))
                    //{
                    //    num = decimal.Parse(row_source["num"].ToString());
                    //}

                    //foreach (DataRow row in ds_mcount.Tables[0].Rows)
                    //{

                    //    DateTime gyny = DateTime.Parse(row["supplyDate"].ToString());//供应年月
                    //    DateTime ghq = DateTime.Parse(row["supplyPlaneDate"].ToString());// 供货期

                    //    if (cm.Count == 1)
                    //    {
                    //        DateTime ghqMonthStartTime;//供货期的起始时间

                    //        int ghqDay = ghq.Day;//供货期

                    //        if (ghqDay <= c.ygyjs)//当前配置结算日期，则按照上月到这个日期小于月计算，大于配置结算日期，则按照这个月到下月计算
                    //        {
                    //            ghqMonthStartTime = DateTime.Parse(ghq.AddMonths(-1).ToString("yyyy-MM-" + c.ygyqs + ""));
                    //        }
                    //        else
                    //        {
                    //            ghqMonthStartTime = DateTime.Parse(ghq.ToString("yyyy-MM-" + c.ygyqs + ""));

                    //        }

                    //        if (DateTime.Compare(gyny, ghqMonthStartTime) < 0)//供应年月小于供货期起始时间 早到货
                    //        {
                    //            if (row["isUpErp"].ToString() == "False")//是否已ERP上传
                    //            {
                    //                //flagEarlyGreen = false;
                    //                row_source["flagEarlyGreen"] = "T";
                    //                break;
                    //            }

                    //        }
                    //    }

                    //}

                    //if (innums == num)
                    //{
                    //    if (row_source["flagEarlyGreen"].ToString() != "T")
                    //    {
                    //        //dt_source.Rows.Remove(row_source);
                    //        removeIndex.Add(i);
                    //    }
                    //}

                    #endregion

                    #region  获取月供应计划详情信息并根据详情信息处理 晚到货情况
                    foreach (DataRow row in ds_mcount.Tables[0].Rows)
                    {
                        if (cm.Count == 1)
                        {
                            #region 本月供应计划起始结束时间 以供应年月为基准
                            DateTime gyny = DateTime.Parse(row["supplyDate"].ToString());//供应年月
                            int gynyDay = gyny.Day;

                            DateTime g_monthEndTime;//供应年月结束时间
                            DateTime g_monthStartTime;//供应年月计划起始时间

                            if (gynyDay <= c.ygyjs)
                            {
                                g_monthStartTime = DateTime.Parse(gyny.AddMonths(-1).ToString("yyyy-MM-" + c.ygyqs + ""));
                                g_monthEndTime = DateTime.Parse(gyny.ToString("yyyy-MM-" + c.ygyjs + ""));
                            }
                            else
                            {
                                g_monthStartTime = DateTime.Parse(gyny.ToString("yyyy-MM-" + c.ygyqs + ""));
                                g_monthEndTime = DateTime.Parse(gyny.AddMonths(1).ToString("yyyy-MM-" + c.ygyjs + ""));
                            }
                            #endregion

                            if (DateTime.Compare(DateTime.Now, g_monthEndTime) > 0)//系统登录时间大于月计划结束时间（以供应年月为基准）晚到货
                            {
                                decimal y_innums = 0;//月供应计划已入库数量
                                decimal y_thisMonthNums = 0;//月供应计划数量

                                if (!string.IsNullOrEmpty(row["thisMonthCount"].ToString()))
                                {
                                    y_thisMonthNums = decimal.Parse(row["thisMonthCount"].ToString());
                                }
                                if (!string.IsNullOrEmpty(row["innums"].ToString()))
                                {
                                    y_innums = decimal.Parse(row["innums"].ToString());
                                }

                                if (y_innums < y_thisMonthNums)//入库数量小于当月计划数量
                                {
                                    //flagLateRed = false;//晚到货标志变红,如果一个计划中既有早到货情况又有晚到货情况，则变红处理
                                    row_source["flagLateRed"] = "T";//晚到货标志变红,如果一个计划中既有早到货情况又有晚到货情况，则变红处理
                                    break;
                                }

                            }


                        }

                    }

                    #endregion

                }

               
            }

            //for (int i = 0; i < dt_source.Rows.Count; i++)
            //{
            //    if (!removeIndex.Contains(i))
            //    {
            //        DataRow row = dt_source.Rows[i];

            //        dt.ImportRow(row);
            //    }

            //}
         
            //return dt;

            return dt_source;

        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton lbn_add = e.Row.FindControl("lbn_add") as LinkButton;//生成月供应计划
                LinkButton lbn_upSupplyDate = e.Row.FindControl("lbn_upSupplyDate") as LinkButton;//修改供货期
                LinkButton lbn_detail = e.Row.FindControl("lbn_detail") as LinkButton;//月供应计划详情
                
                Label lbl_technicalDataStatus = e.Row.FindControl("lbl_technicalDataStatus") as Label;
                Label lbl_supplyDateStatus = e.Row.FindControl("lbl_supplyDateStatus") as Label;
                Label lbl_supplyPlanId = e.Row.FindControl("lbl_supplyPlanId") as Label;
                Label lbl_innums = e.Row.FindControl("lbl_innums") as Label;//已入库数量
                Label lbl_num = e.Row.FindControl("lbl_num") as Label;//总计划数量
                Label lbl_early = e.Row.FindControl("lbl_early") as Label;//早到货情况
                Label lbl_late = e.Row.FindControl("lbl_late") as Label;//晚到货情况

                Label lbl_flagEarlyGreen = e.Row.FindControl("lbl_flagEarlyGreen") as Label;//
                Label lbl_flagLateRed = e.Row.FindControl("lbl_flagLateRed") as Label;//
                Label lbl_isMonthSupplyPlan = e.Row.FindControl("lbl_isMonthSupplyPlan") as Label;//
                Label lbl_equipmentManage = e.Row.FindControl("lbl_equipmentManage") as Label;//设备管理单位
                

                //OldDeailRowMethod(e, lbn_add, lbl_supplyPlanId, lbl_innums, lbl_num, lbl_early, lbl_late);

                if (lbl_isMonthSupplyPlan.Text == "是")//如果已经制定了月供应计划
                {
                    lbn_add.ForeColor = System.Drawing.Color.Red;
                    lbn_add.Attributes.Add("onclick", "javascript:return confirm('已制定了月供应计划，是否继续生成？')");
                }
                if (lbl_flagEarlyGreen.Text == "T")
                {
                    lbl_early.Visible = true;
                }
                else
                {
                    lbl_early.Visible = false;
                }

                if (lbl_flagLateRed.Text == "T")
                {
                    lbl_late.Visible = true;
                }
                else
                {
                    lbl_late.Visible = false;
                }
                if (!string .IsNullOrEmpty(lbl_equipmentManage.Text))
                {
                    lbn_add.Enabled = true;
                }
                else
                {
                    lbn_add.Enabled = false;
                }

                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    if (e.Row.RowType == DataControlRowType.DataRow)
                        e.Row.Cells[i].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
                }

            }
        }

       
        protected void btn_sel_Click(object sender, EventArgs e)
        {
            if (Session["login"] != null)
            {
                DataSet ds = Session["login"] as DataSet;

                int user_id = Convert.ToInt32(ds.Tables[0].Rows[0]["user_id"].ToString());

                Bind(user_id);
            }
        }

        //导出复写
        public override void VerifyRenderingInServerForm(Control control)       //导出
        { }
        //导出excel
        protected void btn_out_Click(object sender, EventArgs e)
        {
            //this.GridView1.AllowPaging = false;

            if (Session["login"] != null)
            {
                DataSet ds = Session["login"] as DataSet;

                int user_id = Convert.ToInt32(ds.Tables[0].Rows[0]["user_id"].ToString());

                //Bind(user_id);
                BindOutExcel(user_id);
            }

            this.GridView1.Columns[0].Visible = false;
            this.GridView1.Columns[1].Visible = false;

            if (this.GridView1.Rows.Count != 0)
            {
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "GB2312";
                Response.AppendHeader("Content-Disposition", "attachment;filename=yuegongjihua.xls");
                //Response.ContentEncoding = System.Text.Encoding.UTF7;
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                Response.ContentType = "application/ms-excel";
                System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
                Response.Output.Write("<H4 align='center'>月供应计划</H4>");
                this.GridView1.RenderControl(oHtmlTextWriter);
                Response.Output.Write(oStringWriter.ToString());
                Response.Flush();
                Response.End();

            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('数据为空，无法导出表格')</script>");

            }

        }

        //绑定导出Excel数据，去除分页
        private void BindOutExcel(int user_id)
        {
            
            int count = 0;//总页数

            string isMonthSupplyPlan = null;

            if (this.rdo_wsc.Checked)//未生成月供计划
            {
                isMonthSupplyPlan = "否";
            }
            if (this.rdo_ysc.Checked)//已生成月供计划
            {
                isMonthSupplyPlan = "是";
            }


            #region 下月供应计划起始结束时间 以当前系统时间为基准
            List<dzs.Model.configinfo> cm = new dzs.BLL.configinfo().GetModelList("");//获取时间结算日期

            DateTime monthEndTime;//本月供应计划结束时间
            DateTime monthStartTime;//本月供应计划起始时间

            dzs.Model.configinfo c = cm[0];
            int day = DateTime.Today.Day;

            if (day <= c.ygyjs)
            {
                monthStartTime = DateTime.Parse(DateTime.Today.ToString("yyyy-MM-" + c.ygyqs + ""));
                monthEndTime = DateTime.Parse(DateTime.Today.AddMonths(1).ToString("yyyy-MM-" + c.ygyjs + ""));
            }
            else
            {
                monthStartTime = DateTime.Parse(DateTime.Today.AddMonths(1).ToString("yyyy-MM-" + c.ygyqs + ""));
                monthEndTime = DateTime.Parse(DateTime.Today.AddMonths(2).ToString("yyyy-MM-" + c.ygyjs + ""));
            }
            #endregion
            DataSet ds = sm.GetListSumInnumsInfo(user_id, monthEndTime, txt_material.Text, txt_projectName.Text,
                txt_supplier.Text, txt_ghqStart.Text, txt_ghqEnd.Text, isMonthSupplyPlan,
                this.AspNetPager1.CurrentPageIndex, this.AspNetPager1.PageSize, out count);

            ds = sm.GetListSumInnumsInfo(user_id, monthEndTime, txt_material.Text, txt_projectName.Text,
                txt_supplier.Text, txt_ghqStart.Text, txt_ghqEnd.Text, isMonthSupplyPlan,
                this.AspNetPager1.CurrentPageIndex, count, out count);

            this.AspNetPager1.RecordCount = count;

            DataTable dt = ds.Tables[0];
 
            DataTable dt_source = dt.Copy();

            dt_source.Columns.Add("flagEarlyGreen", typeof(System.String));//有早到货情况标示
            dt_source.Columns.Add("flagLateRed", typeof(System.String));//有晚到货情况标示
          
            DataTable dt_dealSource = DealEarlyLate(user_id, cm, c, dt_source);
            this.GridView1.DataSource = dt_dealSource;
            this.GridView1.DataBind();
            this.lbl_dsCount.Text = "当前共 " + count + " 条记录";

        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "lbn_add")
            {
                if (e.CommandArgument != null)
                {
                    Session["supplyPlanIdAddMonth"] = e.CommandArgument.ToString();

                    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>OpenPop('FrameAddMonthSupplyInfo.aspx','900px','390px');</script>");
                }
            }
            if (e.CommandName == "lbn_detail")
            {
                if (e.CommandArgument != null)
                {
                    Response.Redirect("ListMonthSupplyPlanDetail.aspx?supplyPlanIdListDetail=" + e.CommandArgument.ToString());

                }
            }
            if (e.CommandName == "outconfirm")
            {
                GridViewRow gvr = (GridViewRow)((Control)e.CommandSource).Parent.Parent;
                string unit, proname, id, jdate, jhnum, wl, supplier;//需用单位，项目名称，采购订单号，合同交货期，招标批次，货物名称,供应商名称
                //int pid = int.Parse(gwSearch.DataKeys[gvr.RowIndex].Value.ToString());    
                jhnum = gvr.Cells[14].Text.Trim();
                wl = gvr.Cells[5].Text.Trim();
                id = gvr.Cells[15].Text.Trim();
                //unit = gvr.Cells[11].Text.Trim();
                unit = gvr.Cells[2].Text.Trim();//主送和供应商回复中经办人都改为了供应商名称
                jdate = gvr.Cells[10].Text.Trim();
                proname = gvr.Cells[3].Text.Trim();
                supplier = gvr.Cells[2].Text.Trim();
                //name = ((Label)gvr.Cells[25].Controls[1]).Text;
                //fax = ((Label)gvr.Cells[26].Controls[1]).Text;
                string file = ExWord.ExportToWordconfirm(unit, jdate, jhnum, proname, id, wl);
                FileInfo DownloadFile = new FileInfo(file);
                Response.Clear();
                Response.ClearHeaders();
                Response.Buffer = false;
                Response.ContentType = "application/octet-stream";
                Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.Name, System.Text.Encoding.UTF8));
                Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
                Response.WriteFile(DownloadFile.FullName);
                Response.Flush();
                Response.End();

            }
            if (e.CommandName == "outex")
            {
                //int index = int.Parse(e.CommandArgument.ToString());
                GridViewRow gvr = (GridViewRow)((Control)e.CommandSource).Parent.Parent;
                string unit, proname, id, jdate, jhnum, wl, supplier;
                //int pid = int.Parse(gwSearch.DataKeys[gvr.RowIndex].Value.ToString());
                jhnum = gvr.Cells[14].Text.Trim();
                wl = gvr.Cells[5].Text.Trim();
                id = gvr.Cells[15].Text.Trim();
                //unit = gvr.Cells[11].Text.Trim();
                unit = gvr.Cells[2].Text.Trim();//主送和供应商回复中经办人都改为了供应商名称
                jdate = gvr.Cells[10].Text.Trim();
                proname = gvr.Cells[3].Text.Trim();
                supplier = gvr.Cells[2].Text.Trim();
                string file = ExWord.ExportToWordExped(unit, jdate, jhnum, proname, id, wl);
                FileInfo DownloadFile = new FileInfo(file);
                Response.Clear();
                Response.ClearHeaders();
                Response.Buffer = false;
                Response.ContentType = "application/octet-stream";
                Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.Name, System.Text.Encoding.UTF8));
                Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
                Response.WriteFile(DownloadFile.FullName);
                Response.Flush();
                Response.End();

            }
            if (e.CommandName == "upSupplyDate")//修改供货期
            {
                if (e.CommandArgument != null)
                {
                    Session["updateSupplyDateId"] = e.CommandArgument.ToString();

                    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>OpenPop('FramePopUpdateSupplyDate.aspx','500px','290px');</script>");
                }
            }
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            if (Session["login"] != null)
            {
                DataSet ds = Session["login"] as DataSet;

                int user_id = Convert.ToInt32(ds.Tables[0].Rows[0]["user_id"].ToString());

                Bind(user_id);
            }
        }

        //批量生成月供应计划
        protected void btn_addMon_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.GridView1.Rows.Count; i++)
            {
                CheckBox cbo = this.GridView1.Rows[i].FindControl("cbo_check") as CheckBox;

                if (cbo != null && cbo.Checked)
                {
                    Label lbl = this.GridView1.Rows[i].FindControl("lbl_supplyPlanIdV") as Label;
                    Label lbl_equipmentManage = this.GridView1.Rows[i].FindControl("lbl_equipmentManage") as Label;

                    if (!string.IsNullOrEmpty(lbl.Text) && !string.IsNullOrEmpty(lbl_equipmentManage.Text))
                    {
                        string supplyPlanId = lbl.Text;
                        DataSet ds = new Maticsoft.BLL.supplyPlan().GetList(" supplyPlanId=" + supplyPlanId);

                        Maticsoft.Model.supplyPlan s = new Maticsoft.BLL.supplyPlan().GetModel(int.Parse(supplyPlanId));
                        decimal count = 0;
                        decimal innums = 0;
                        decimal maxNums = 0;
                        try
                        {
                            DataSet ds_innums = new Maticsoft.BLL.supplyPlan().GetListAllInums(" supplyPlanId=" + supplyPlanId);

                            count = decimal.Parse(ds.Tables[0].Rows[0]["num"].ToString());
                            innums = decimal.Parse(ds_innums.Tables[0].Rows[0]["innums"].ToString());//计划已入库数量

                            maxNums = s.num.Value - innums;
                            
                            if (count <= maxNums)//小于等于总计划数量
                            {
                                string equipmentManage = ds.Tables[0].Rows[0]["equipmentManage"].ToString();

                                if (!string.IsNullOrEmpty(equipmentManage))
                                {
                                    Maticsoft.BLL.monthSupplayPlan msm = new Maticsoft.BLL.monthSupplayPlan();
                                    Maticsoft.Model.monthSupplayPlan ms = new Maticsoft.Model.monthSupplayPlan();

                                    //ms.arrivalAddress = this.ddl_arrivalAddress.SelectedValue;
                                    ms.equipmentManage = equipmentManage;//设备管理单位
                                    //ms.contactWay = this.txt_contactWay.Text;
                                    //ms.linkman = this.txt_linkman.Text;
                                    ms.supplyDate = DateTime.Parse(ds.Tables[0].Rows[0]["supplyDate"].ToString());//供应年月
                                    ms.thisMonthCount = count;
                                    ms.supplyPlanId = int.Parse(supplyPlanId);
                                    ms.status = "1";
                                    ms.isGoodsQualityStatus = false;
                                    ms.result = "未完成";
                                    ms.createTime = DateTime.Now;//计划生成时间

                                    if (msm.Add(ms) > 0)
                                    {
                                        if (Session["login"] != null)
                                        {
                                          
                                            DataSet ds_login = Session["login"] as DataSet;

                                            int user_id = Convert.ToInt32(ds_login.Tables[0].Rows[0]["user_id"].ToString());

                                            Bind(user_id);
                                        }
                                    }
                                }
                                
                            }
                            else
                            {
                                //Maticsoft.Common.MessageBox.Show(this, "本月计划数量应小于等于(总计划数量-已入库数量)！");
                            }
                        }
                        catch (Exception)
                        {
                            //Maticsoft.Common.MessageBox.Show(this, "计划数量请填写数字！");
                        }
                    }
                }

            }
        }
        protected void btn_reload_Click(object sender, EventArgs e)
        {
            if (Session["login"] != null)
            {
                DataSet ds = Session["login"] as DataSet;

                int user_id = Convert.ToInt32(ds.Tables[0].Rows[0]["user_id"].ToString());

                Bind(user_id);
            }
        }


        //旧方法，已不再使用
        private void OldDeailRowMethod(GridViewRowEventArgs e, LinkButton lbn_add, Label lbl_supplyPlanId, Label lbl_innums,
            Label lbl_num, Label lbl_early, Label lbl_late)
        {
            decimal innums = 0;
            decimal num = 0;

            if (!string.IsNullOrEmpty(lbl_innums.Text))
            {
                innums = decimal.Parse(lbl_innums.Text);

            }
            if (!string.IsNullOrEmpty(lbl_num.Text))
            {
                num = decimal.Parse(lbl_num.Text);
            }

            #region 获取月供应计划详情列表 ds_mcount
            DataSet ds_mcount = null;
            if (Session["login"] != null)
            {
                DataSet ds = Session["login"] as DataSet;
                int user_id = Convert.ToInt32(ds.Tables[0].Rows[0]["user_id"].ToString());
                Maticsoft.BLL.monthSupplayPlan sms = new Maticsoft.BLL.monthSupplayPlan();

                string str = "  supplyPlanUser= " + user_id + " and supplyPlanId=" + lbl_supplyPlanId.Text;

                if (!string.IsNullOrEmpty(txt_material.Text))
                {
                    str += " and material like '%" + txt_material.Text + "%' ";
                }
                if (!string.IsNullOrEmpty(txt_projectName.Text))
                {
                    str += " and projectName like '%" + txt_projectName.Text + "%' ";
                }

                ds_mcount = sms.GetListInnums(str);
            }
            #endregion

            #region 判断是否上传ERP flagEarlyGreen为Flase时未全部上传ERP，True时全部上传ERP,晚到货情况flagLateRed为False时有晚到货
            bool flagEarlyGreen = true;//早到货变绿状态
            bool flagLateRed = true;//晚到货变红状态

            if (ds_mcount != null)
            {
                foreach (DataRow row in ds_mcount.Tables[0].Rows)
                {
                    DateTime gyny = DateTime.Parse(row["supplyDate"].ToString());//供应年月
                    DateTime ghq = DateTime.Parse(row["supplyPlaneDate"].ToString());// 供货期

                    List<dzs.Model.configinfo> cm = new dzs.BLL.configinfo().GetModelList("");//获取时间结算日期

                    if (cm.Count == 1)
                    {
                        dzs.Model.configinfo c = cm[0];

                        DateTime ghqMonthStartTime;//供货期的起始时间

                        int ghqDay = ghq.Day;//供货期

                        if (ghqDay < c.ygyjs)//当前日期小于配置结算日期，则按照上月到这个月计算，大于配置结算日期，则按照这个月到下月计算
                        {
                            ghqMonthStartTime = DateTime.Parse(ghq.AddMonths(-1).ToString("yyyy-MM-" + c.ygyqs + ""));
                        }
                        else
                        {
                            ghqMonthStartTime = DateTime.Parse(ghq.ToString("yyyy-MM-" + c.ygyqs + ""));

                        }

                        if (DateTime.Compare(gyny, ghqMonthStartTime) < 0)//供应年月小于供货期起始时间 早到货
                        {
                            if (row["isUpErp"].ToString() == "False")//是否已ERP上传
                            {
                                flagEarlyGreen = false;
                                break;
                            }

                        }
                    }

                }

                foreach (DataRow row in ds_mcount.Tables[0].Rows)
                {
                    List<dzs.Model.configinfo> cm = new dzs.BLL.configinfo().GetModelList("");//获取时间结算日期

                    if (cm.Count == 1)
                    {
                        dzs.Model.configinfo c = cm[0];

                        #region 本月供应计划起始结束时间 以供应年月为基准
                        DateTime gyny = DateTime.Parse(row["supplyDate"].ToString());//供应年月
                        int gynyDay = gyny.Day;

                        DateTime g_monthEndTime;//供应年月结束时间
                        DateTime g_monthStartTime;//供应年月计划起始时间

                        if (gynyDay < c.ygyjs)
                        {
                            g_monthStartTime = DateTime.Parse(gyny.AddMonths(-1).ToString("yyyy-MM-" + c.ygyqs + ""));
                            g_monthEndTime = DateTime.Parse(gyny.ToString("yyyy-MM-" + c.ygyjs + ""));
                        }
                        else
                        {
                            g_monthStartTime = DateTime.Parse(gyny.ToString("yyyy-MM-" + c.ygyqs + ""));
                            g_monthEndTime = DateTime.Parse(gyny.AddMonths(1).ToString("yyyy-MM-" + c.ygyjs + ""));
                        }
                        #endregion


                        //当月月供应计划最晚时间大于供应年月，属于晚到货情况
                        if (DateTime.Compare(DateTime.Now, g_monthEndTime) > 0)//系统登录时间大于月计划结束时间（以供应年月为基准）晚到货
                        {
                            decimal y_innums = 0;//月供应计划已入库数量
                            decimal y_thisMonthNums = 0;//月供应计划数量

                            if (!string.IsNullOrEmpty(row["thisMonthCount"].ToString()))
                            {
                                y_thisMonthNums = decimal.Parse(row["thisMonthCount"].ToString());
                            }
                            if (!string.IsNullOrEmpty(row["innums"].ToString()))
                            {
                                y_innums = decimal.Parse(row["innums"].ToString());
                            }

                            if (y_innums < y_thisMonthNums)//入库数量小于当月计划数量
                            {
                                flagLateRed = false;//晚到货标志变红,如果一个计划中既有早到货情况又有晚到货情况，则变红处理
                                break;
                            }

                        }


                    }

                }
            }

            #endregion

            #region
            if (innums == num)//入库数量=总计划数量，即计划完成了
            {
                if (!flagEarlyGreen)//判断有无早到货情况，如果有早到货且没有点击上传ERP，则计划完成也要显示
                {
                    lbn_add.Enabled = true;

                    e.Row.Visible = true;

                    if (ds_mcount != null)
                    {
                        if (ds_mcount.Tables[0].Rows.Count > 0)//如果已经制定了月供应计划
                        {
                            lbn_add.ForeColor = System.Drawing.Color.Red;
                        }
                        if (!flagEarlyGreen)//有早到货情况
                        {
                            //lbn_detail.ForeColor = System.Drawing.Color.Green;
                            lbl_early.Visible = true;
                        }
                        else
                        {
                            lbl_early.Visible = false;
                        }
                        if (!flagLateRed)//有晚到货情况
                        {
                            lbl_late.Visible = true;
                        }
                        else
                        {
                            lbl_late.Visible = false;
                        }
                    }

                }
                else
                {
                    e.Row.Visible = false;
                }


            }
            else
            {
                e.Row.Visible = true;

                if (ds_mcount != null)
                {
                    if (ds_mcount.Tables[0].Rows.Count > 0)//如果已经制定了月供应计划
                    {
                        lbn_add.ForeColor = System.Drawing.Color.Red;
                    }
                    if (!flagEarlyGreen)
                    {
                        //lbn_detail.ForeColor = System.Drawing.Color.Green;
                        lbl_early.Visible = true;
                    }
                    else
                    {
                        lbl_early.Visible = false;
                    }

                    if (!flagLateRed)//有晚到货情况
                    {
                        lbl_late.Visible = true;
                    }
                    else
                    {
                        lbl_late.Visible = false;
                    }

                }


            }
            #endregion
        }
        //更新备注
        protected void btn_upRemark_Click(object sender, EventArgs e)
        {
            bool flag = false;
            for (int i = 0; i < this.GridView1.Rows.Count; i++)
            {
                CheckBox cbo = this.GridView1.Rows[i].FindControl("cbo_check") as CheckBox;

                if (cbo != null && cbo.Checked)
                {
                    flag = true;
                }
            }

            if (flag)
            {
                Maticsoft.BLL.supplyPlan sm = new Maticsoft.BLL.supplyPlan ();
                for (int i = 0; i < this.GridView1.Rows.Count; i++)
                {
                    CheckBox cbo = this.GridView1.Rows[i].FindControl("cbo_check") as CheckBox;

                    if (cbo != null && cbo.Checked)
                    {
                        Label lbl = this.GridView1.Rows[i].FindControl("lbl_supplyPlanIdV") as Label;

                        if (!string.IsNullOrEmpty(lbl.Text))
                        {
                            string supplyPlanId = lbl.Text;

                            string remark = this.txt_remark.Text;

                            Maticsoft.Model.supplyPlan s = sm.GetModel(int.Parse(supplyPlanId));

                            s.remark = remark;

                            sm.Update(s);
                        }
                    }
                }

                if (Session["login"] != null)
                {
                    this.txt_remark.Text = "";

                    DataSet ds = Session["login"] as DataSet;

                    int user_id = Convert.ToInt32(ds.Tables[0].Rows[0]["user_id"].ToString());

                    Bind(user_id);
                }

            }
            else
            {
                Maticsoft.Common.MessageBox.Show(this, "请选择要修改的备注提醒！");
            }
        }

        //设置设备管理单位
        protected void btn_setEqu_Click(object sender, EventArgs e)
        {
            if (this.ddl_equipmentMan.SelectedValue == "-1")
            {
                Maticsoft.Common.MessageBox.Show(this, "请选择设备管理单位！");
            }
            bool flag = false;
            for (int i = 0; i < this.GridView1.Rows.Count; i++)
            {
                CheckBox cbo = this.GridView1.Rows[i].FindControl("cbo_check") as CheckBox;

                if (cbo != null && cbo.Checked)
                {
                    flag = true;
                }
            }

            if (flag)
            {
                Maticsoft.BLL.supplyPlan sm = new Maticsoft.BLL.supplyPlan();
                for (int i = 0; i < this.GridView1.Rows.Count; i++)
                {
                    CheckBox cbo = this.GridView1.Rows[i].FindControl("cbo_check") as CheckBox;

                    if (cbo != null && cbo.Checked)
                    {
                        Label lbl = this.GridView1.Rows[i].FindControl("lbl_supplyPlanIdV") as Label;

                        if (!string.IsNullOrEmpty(lbl.Text))
                        {
                            string supplyPlanId = lbl.Text;

                            string equimpmentManage = this.ddl_equipmentMan.SelectedItem.Text;

                            Maticsoft.Model.supplyPlan s = sm.GetModel(int.Parse(supplyPlanId));

                            s.equipmentManage = equimpmentManage;

                            sm.Update(s);
                        }
                    }
                }

                if (Session["login"] != null)
                {
                    this.txt_remark.Text = "";

                    DataSet ds = Session["login"] as DataSet;

                    int user_id = Convert.ToInt32(ds.Tables[0].Rows[0]["user_id"].ToString());

                    Bind(user_id);

                    Maticsoft.Common.MessageBox.Show(this, "修改成功！");
                }

            }
            else
            {
                Maticsoft.Common.MessageBox.Show(this, "请选择要修改的设备管理单位！");
            }
        }

    }
}